
//  const gcoord = require('../../gcoord');
import gcoord from '.././miniprogram_npm/gcoord/dist/gcoord'
class BMapWX {

  /**
   * 百度地图微信小程序API类
   *
   * @constructor
   */
  constructor(param) {
    this.ak = param["ak"];
    this.token = param["token"];
    //console.log(param["token"], param["ak"]);
  }

  /**
   * 使用微信接口进行定位
   *
   * @param {string} type 坐标类型
   * @param {Function} success 成功执行
   * @param {Function} fail 失败执行
   * @param {Function} complete 完成后执行
   */

  getWXLocation(type, success, fail, complete) {
    type = type || 'gcj02',
      success = success || function () {};
    fail = fail || function () {};
    complete = complete || function () {};
    getApp().globalData.getLocation({
      type: type,
      success: success,
      fail: fail,
      complete: complete
    });
  }

  /**
   * POI周边检索
   *
   * @param {Object} param 检索配置
   * 参数对象结构可以参考
   * http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi
   */
  search(param) {
    // console.log("++++", param);
    var that = this;
    param = param || {};
    let searchparam = {
      query: param["query"],
      scope: param["scope"] || 1,
      filter: param["filter"] || '',
      coord_type: param["coord_type"] || 2,
      page_size: param["page_size"] || 10,
      page_num: param["page_num"] || 0,
      output: param["output"] || 'json',
      ak: that.ak,
      userLng: "",
      userLat: "",
      distance: "5.0",
      pageBO: {
        pageSize: "",
        pageNum: ""
      },
      sn: param["sn"] || '',
      timestamp: param["timestamp"] || '',
      radius: param["radius"] || 2000,
      ret_coordtype: 'gcj02ll'
    };
    //console.log("+++++++++++++++++++++++++++++++++", searchparam);
    let otherparam = {
      iconPath: param["iconPath"],
      iconTapPath: param["iconTapPath"],
      width: param["width"] || 20,
      height: param["height"] || 30,
      alpha: param["alpha"] || 1,
      success: param["success"] || function () {},
      fail: param["fail"] || function () {}
    };
    let type = 'gcj02';
    //console.log(otherparam);
    let locationsuccess = function (result) {
      searchparam["userLng"] = result["longitude"];
      searchparam["userLat"] = result["latitude"]
      getApp().globalData.request("/map/nearBy", {
          query: param["query"],
          scope: param["scope"] || 1,
          filter: param["filter"] || '',
          coord_type: param["coord_type"] || 2,
          page_size: param["page_size"] || 10,
          page_num: param["page_num"] || 0,
          output: param["output"] || 'json',
          ak: that.ak,
          userLng: result["longitude"],
          userLat: result["latitude"],
          distance: "5.0",
          pageBO: {
            pageSize: 200,
            pageNum: 1
          },
          sn: param["sn"] || '',
          timestamp: param["timestamp"] || '',
          radius: param["radius"] || 2000,
          ret_coordtype: 'gcj02ll'
        }, "post")
        .then((data) => {
          //请求成功接收到的res
          // console.log("请求成功接收到的res",data);
          let res = data["rows"];
          if (data["code"] === 200) {
            let poiArr = res
            //console.log(poiArr);
            // outputRes 包含两个对象，
            // originalData为百度接口返回的原始数据
            // wxMarkerData为小程序规范的marker格式
            let outputRes = {};
            outputRes["originalData"] = res;
            outputRes["wxMarkerData"] = [];
            for (let i = 0; i < poiArr.length; i++) {
              var result = gcoord.transform(
               [poiArr[i]["longitude"], poiArr[i]["latitude"]],    // 经纬度坐标
                gcoord.BD09,               // 当前坐标系
                gcoord.GCJ02                 // 目标坐标系
              );
              outputRes["wxMarkerData"][i] = {
                id: i,
                latitude: result[1],
                longitude:result[0],
                title: poiArr[i]["d2CorpName"],
                iconPath: otherparam["iconPath"] || 1,
                iconTapPath: otherparam["iconTapPath"],
                address: poiArr[i]["address"],
                telephone: poiArr[i]["telephone"],
                alpha: otherparam["alpha"],
                width: otherparam["width"],
                height: otherparam["height"]
              }
            }
            otherparam.success(outputRes);
          } else {
            otherparam.fail({
              errMsg: res["message"],
              statusCode: res["status"]
            });
          }
        }).catch(err => {
        })
    }
    let locationfail = function (result) {
      otherparam.fail(result);
    };
    let locationcomplete = function (result) {};
    if (!param["location"]) {
      that.getWXLocation(type, locationsuccess, locationfail, locationcomplete);
    } else {
      let longitude = param.location.split(',')[1];
      let latitude = param.location.split(',')[0];
      let errMsg = 'input location';
      let res = {
        errMsg: errMsg,
        latitude: latitude,
        longitude: longitude
      };
      locationsuccess(res);
    }
  }

  /**
   * sug模糊检索
   *
   * @param {Object} param 检索配置
   * 参数对象结构可以参考
   * http://lbsyun.baidu.com/index.php?title=webapi/place-suggestion-api
   */
  suggestion(param) {
    var that = this;
    param = param || {};
    let suggestionparam = {
      query: param["query"] || '',
      region: param["region"] || '全国',
      city_limit: param["city_limit"] || false,
      output: param["output"] || 'json',
      ak: that.ak,
      sn: param["sn"] || '',
      timestamp: param["timestamp"] || '',
      ret_coordtype: 'gcj02ll'
    };
    let otherparam = {
      success: param["success"] || function () {},
      fail: param["fail"] || function () {}
    };
    console.log("+50+5+0+++00", suggestionparam);
    getApp().globalData.request("/map/queryCorpInfoByKeyWord", {
        keyWord: param["query"] || '',
        region: param["region"] || '全国',
        city_limit: param["city_limit"] || false,
        output: param["output"] || 'json',
        ak: that.ak,
        token: param["token"],
        sn: param["sn"] || '',
        timestamp: param["timestamp"] || '',
        ret_coordtype: 'gcj02ll'
      }, "post")
      .then((data) => {
        //请求成功接收到的res
        console.log("+++++6464", data);
        let res = data["data"];
        if (res["status"] === 0) {
          otherparam.success(res);
        } else {
          otherparam.fail({
            errMsg: res["message"],
            statusCode: res["status"]
          });

        }

      }).catch(err => {

      })
    // getApp().globalData.request("/map/queryCorpInfoByKeyWord", {
    //   query: param["query"] || '',
    //   region: param["region"] || '全国',
    //   city_limit: param["city_limit"] || false,
    //   output: param["output"] || 'json',
    //   ak: that.ak,
    //   keyWord:that.name, 
    //   sn: param["sn"] || '',
    //   timestamp: param["timestamp"] || '',
    //   ret_coordtype: 'gcj02ll'
    //   }, "post")
    //   .then((data) => {
    //     //请求成功接收到的res
    //   console.log("+++++6464", data["data"]);
    //     let res = data["data"];
    //     if (res["status"] === 0) {
    //       otherparam.success(res);
    //     } else {
    //       otherparam.fail({
    //         errMsg: res["message"],
    //         statusCode: res["status"]
    //       });

    //     }

    //   }).catch(err => {

    //   })
    // wx.request({
    //   url: 'https://fintech-wx.szjrgzjg.com//map/nearBy',
    //   data: suggestionparam,
    //   header: {
    //     "content-type": "application/json",
    //     token:that.token
    //   },
    //   method: 'post',
    //   success(data) {
    //     let res = data["data"];
    //     if (res["status"] === 0) {
    //       otherparam.success(res);
    //     } else {
    //       otherparam.fail({
    //         errMsg: res["message"],
    //         statusCode: res["status"]
    //       });
    //     }
    //   },
    //   fail(data) {
    //     otherparam.fail(data);
    //   }
    // });
  }

  /**
   * rgc检索（逆地理编码：经纬度->地点描述）
   * 
   * @param {Object} param 检索配置
   * 参数对象结构可以参考
   * https://lbs.baidu.com/index.php?title=webapi/guide/webservice-geocoding-abroad
   * 
   */

  regeocoding(param) {
   
    var that = this
    let type = 'gcj02';
    var data1
    let locationsuccess = function (result) {
      console.log(result["latitude"], result["longitude"]);
      return getApp().globalData.request("/map/inverseGeocode", {
          ak: that.ak,
          lat: result["latitude"],
          lng: result["longitude"],
        }, "post")
        .then((data) => {
          console.log(data);
          data1=data
          
          if (data.code === 200) {
            let poiObj = data;
            // outputRes 包含两个对象：
            // originalData为百度接口返回的原始数据
            // wxMarkerData为小程序规范的marker格式
            let outputRes = {};
            outputRes["originalData"] = data;
            outputRes["wxMarkerData"] = [];
            outputRes["wxMarkerData"][0] = {
              id: 0,
              latitude: result["latitude"],
              longitude: result["longitude"],
              address:data.data,
              iconPath: otherparam["iconPath"],
              iconTapPath: otherparam["iconTapPath"],
              desc: poiObj["sematic_description"],
              business: poiObj["business"],
              alpha: otherparam["alpha"],
              width: otherparam["width"],
              height: otherparam["height"]
            }
            otherparam.success(poiObj);
            return data
          } else {
            otherparam.fail({
              errMsg: res["message"],
              statusCode: res["status"]
            });

          }

        }).catch(err => {

        })
        return data1
      // wx.request({
      //   url: 'https://fintech-wx.szjrgzjg.com//map/nearBy',
      //   data: regeocodingparam,
      //   header: {
      //     "content-type": "application/json",
      //     token: that.token
      //   },
      //   method: 'post',
      //   success(data) {
      //     let res = data["data"];
      //     if (res["status"] === 0) {
      //       let poiObj = res["result"];
      //       // outputRes 包含两个对象：
      //       // originalData为百度接口返回的原始数据
      //       // wxMarkerData为小程序规范的marker格式
      //       let outputRes = {};
      //       outputRes["originalData"] = res;
      //       outputRes["wxMarkerData"] = [];
      //       outputRes["wxMarkerData"][0] = {
      //         id: 0,
      //         latitude: result["latitude"],
      //         longitude: result["longitude"],
      //         address: poiObj["formatted_address"],
      //         iconPath: otherparam["iconPath"],
      //         iconTapPath: otherparam["iconTapPath"],
      //         desc: poiObj["sematic_description"],
      //         business: poiObj["business"],
      //         alpha: otherparam["alpha"],
      //         width: otherparam["width"],
      //         height: otherparam["height"]
      //       }
      //       otherparam.success(outputRes);
      //     } else {
      //       otherparam.fail({
      //         errMsg: res["message"],
      //         statusCode: res["status"]
      //       });
      //     }
      //   },
      //   fail(data) {
      //     otherparam.fail(data);
      //   }
      // });
    };
    let locationfail = function (result) {
      otherparam.fail(result);
    }
    let locationcomplete = function (result) {};
    if (!param["location"]) {
      that.getWXLocation(type, locationsuccess, locationfail, locationcomplete);
    } else {
      let longitude = param.location.split(',')[1];
      let latitude = param.location.split(',')[0];
      let errMsg = 'input location';
      let res = {
        errMsg: errMsg,
        latitude: latitude,
        longitude: longitude
      };
      locationsuccess(res);
    }
  }

  /**
   * gc检索（地理编码：地点->经纬度）
   *
   * @param {Object} param 检索配置
   * 参数对象结构可以参考
   * https://lbs.baidu.com/index.php?title=webapi/guide/webservice-geocoding
   * 
   */
  geocoding(param) {
    var that = this;
    param = param || {};
    let geocodingparam = {
      address: param["address"] || '',
      city: param["city"] || '',
      ret_coordtype: param["coordtype"] || 'gcj02ll',
      ak: that.ak,
      sn: param["sn"] || '',
      output: param["output"] || 'json',
      callback: param["callback"] || function () {}
    };
    let otherparam = {
      iconPath: param["iconPath"],
      iconTapPath: param["iconTapPath"],
      width: param["width"],
      height: param["height"],
      alpha: param["alpha"] || 1,
      success: param["success"] || function () {},
      fail: param["fail"] || function () {}
    };
    if (param["address"]) {
      wx.request({
        url: 'https://fintech-wx.szjrgzjg.com//map/nearBy',
        data: geocodingparam,
        header: {
          "content-type": "application/json"
        },
        method: 'post',
        success(data) {
          let res = data["data"];
          if (res["status"] === 0) {
            let poiObj = res["result"];
            // outputRes 包含两个对象：
            // originalData为百度接口返回的原始数据
            // wxMarkerData为小程序规范的marker格式
            let outputRes = res;
            outputRes["originalData"] = res;
            outputRes["wxMarkerData"] = [];
            outputRes["wxMarkerData"][0] = {
              id: 0,
              latitude: poiObj["location"]["lat"],
              longitude: poiObj["location"]["lng"],
              iconPath: otherparam["iconPath"],
              iconTapPath: otherparam["iconTapPath"],
              alpha: otherparam["alpha"],
              width: otherparam["width"],
              height: otherparam["height"]
            }
            otherparam.success(outputRes);
          } else {
            otherparam.fail({
              errMsg: res["message"],
              statusCode: res["status"]
            });
          }
        },
        fail(data) {
          otherparam.fail(data);
        }
      });
    } else {
      let errMsg = 'input address!';
      let res = {
        errMsg: errMsg
      };
      otherparam.fail(res);
    }
  }

  /**
   * 天气检索
   *
   * @param {Object} param 检索配置
   */
  weather(param) {
    var that = this;
    param = param || {};
    let weatherparam = {
      coord_type: param["coord_type"] || 'gcj02',
      output: param["output"] || 'json',
      ak: that.ak,
      sn: param["sn"] || '',
      timestamp: param["timestamp"] || ''
    };
    let otherparam = {
      success: param["success"] || function () {},
      fail: param["fail"] || function () {}
    };
    let type = 'gcj02';
    let locationsuccess = function (result) {
      weatherparam["location"] = result["longitude"] + ',' + result["latitude"];
      wx.request({
        url: 'https://api.map.baidu.com/telematics/v3/weather',
        data: weatherparam,
        header: {
          "content-type": "application/json"
        },
        method: 'post',
        success(data) {
          let res = data["data"];
          if (res["error"] === 0 && res["status"] === 'success') {
            let weatherArr = res["results"];
            // outputRes 包含两个对象，
            // originalData为百度接口返回的原始数据
            // wxMarkerData为小程序规范的marker格式
            let outputRes = {};
            outputRes["originalData"] = res;
            outputRes["currentWeather"] = [];
            outputRes["currentWeather"][0] = {
              currentCity: weatherArr[0]["currentCity"],
              pm25: weatherArr[0]["pm25"],
              date: weatherArr[0]["weather_data"][0]["date"],
              temperature: weatherArr[0]["weather_data"][0]["temperature"],
              weatherDesc: weatherArr[0]["weather_data"][0]["weather"],
              wind: weatherArr[0]["weather_data"][0]["wind"]
            };
            otherparam.success(outputRes);
          } else {
            otherparam.fail({
              errMsg: res["message"],
              statusCode: res["status"]
            });
          }
        },
        fail(data) {
          otherparam.fail(data);
        }
      });
    }
    let locationfail = function (result) {
      otherparam.fail(result);
    }
    let locationcomplete = function (result) {}
    if (!param["location"]) {
      that.getWXLocation(type, locationsuccess, locationfail, locationcomplete);
    } else {
      let longitude = param.location.split(',')[0];
      let latitude = param.location.split(',')[1];
      let errMsg = 'input location';
      let res = {
        errMsg: errMsg,
        latitude: latitude,
        longitude: longitude
      };
      locationsuccess(res);
    }
  }
}

module.exports.BMapWX = BMapWX;